/*
The dev.c file implements the Devices file system
*/


#include <globals.h>
#include <klib.h>
#include <panic.h>
#include <linkedlist.h>

#include <dev.h>

//Private Includes
#include <dev_info.h>


/* Data structures */
ptr_list_t device_list=NULL;

/* Private functions prototypes */


/* Functions implementation */


/* Public Functions implementation */

void dev_initialize(void)
  {
    printf("Initializing device file system...\n");

    // initialize devices list
    device_list=llist_make_list();

    return;
  }

// call-back function to add a bus 
// it will be called by the bus driver initialization routine
int dev_add_bus(struct bus_type *bus)
  {
    return DEV_ERR_NONE;
  }

// call-back function to add a device
// it will be called by the bus driver device enumerator
int dev_add_device(struct dev_device *device)
  {
    // check whether already present
    if (dev_find_device(device->name,NULL)==DEV_ERR_NONE)
      return DEV_ERR_OVERWRITE;

    // if we're here then the device isn't on the list
    // so we can add it
    llist_add_last(device_list,device);

    return DEV_ERR_NONE;
  }

// this function looks for a device in the list accessing it by name
// the corresponding device is returned in the "device" pointer
// if it is NULL, then nothing is returned there
int dev_find_device(char *name,struct dev_device **device)
  {
    struct dev_device *curr_dev;
    ptr_iterator_t iter;
    int found;


    // assume we have found nothing
    if (device!=NULL)
      *device=NULL;

    found=0;
    
    // get iterator on devices
    iter=llist_get_nodes(device_list);
    
    while (llist_iter_has_next(iter))
      {
	curr_dev=(struct dev_device *)llist_iter_next(iter);
	
	// Have we found it?
	if (!strcmp(curr_dev->name,name))
	  {
	    if (device!=NULL)
	      *device=curr_dev;

	    found=1;

	    break;
	  }
      }

    free(iter);

    return found ? DEV_ERR_NONE : DEV_ERR_NOT_FOUND;
  }

void dev_print_list(void)
  {
    struct dev_device *dev;
    ptr_iterator_t iter;

    // get iterator on devices
    iter=llist_get_nodes(device_list);
    
    while (llist_iter_has_next(iter))
      {
	dev=(struct dev_device *)llist_iter_next(iter);
	printf("Device: [%d,%d] %s\n",dev->major,dev->minor,dev->name);
      }

    free(iter);
  }
